package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    //计算前12个月的会员增长情况
    @RequestMapping("/getMemberReport")
    public Result report(){
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        //得到从当前时间起，往后推十二月
        calendar.add(Calendar.MONTH , -12);
        for (int i = 1; i <= 12 ; i++) {
            //从上面得到的前12个月，在循环得到往后的每一个月
            calendar.add(Calendar.MONTH , 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        List memberCount = memberService.findMemberCountByMonths(months);
        Map map = new HashMap();
        map.put("months" , months);
        map.put("memberCount" ,memberCount);
        return new Result(true , MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS , map);

    }

    /*public static void main(String[] args) throws Exception {
        Calendar calendar = Calendar.getInstance();
        //得到当前时间往前推12个月
        calendar.add(Calendar.MONTH , -12);
       *//* Date time = calendar.getTime();
        System.out.println(DateUtils.parseDate2String(time));*//*
        for (int i = 1; i <= 12; i++) {
            calendar.add(Calendar.MONTH , 1);
            Date time = calendar.getTime();
            System.out.println(new SimpleDateFormat("yyyy.MM").format(time));
        }
    }*/

    //套餐预约百分比
   /* @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        List setmealNames = new ArrayList();
        setmealNames.add("入职体检");
        setmealNames.add("健康爸妈");
        //查询所有的套餐名称
        List<String> list = setmealService.findSetmealByName();
        Map map1 = new HashMap();
        List setmealNames = new ArrayList();
        List value = orderService.findByOrderByCount();
        map1.put("name" , list);
        for (String setmealName : list) {
            setmealNames.add(setmealName);
            map1.put("name" , setmealName);
            map1.put("value" , value);
        }

        List<Map> setmealCount = new ArrayList<>();
        List value = orderService.findByOrderByCount();
        for (Object value : list1) {
            map1.put("value" , value);
        }
        map1.put("value" , value);
        map1.put("name" , setmealNames);
        map1.put("value" , value);
        Map map2 = new HashMap();
        map2.put("name" , "健康爸妈");
        map2.put("value" , 150);
        setmealCount.add(map2);
        setmealCount.add(map1);

        List<String> setmealByName = setmealService.findSetmealByName();
        List byOrderByCount = orderService.findByOrderByCount();

        List<String> setmealNames = new ArrayList<>();
        for (String name : setmealByName) {
            setmealNames.add(name);
        }

        List<Map> setmealCount = new ArrayList<>();
        Map map1 = new HashMap();
        for (String name : setmealByName) {
            map1.put("name" , name);
            for (Object count : byOrderByCount) {
                map1.put("vale" , count);
            }
            setmealCount.add(map1);
        }

        Map map = new HashMap();
        map.put("setmealNames" , setmealNames);
        map.put("setmealCount" , setmealCount);
        return new Result(true , MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS , map);
    }*/

   //套餐预约占比
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            List<Map> setmealCount = setmealService.findSetmealByNameAndCount();
            List setmealNames = new ArrayList();
            for (Map map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            Map map = new HashMap();
            map.put("setmealNames" , setmealNames);
            map.put("setmealCount" , setmealCount);
            return new Result(true , MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS , map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        /*Map map = new HashMap();
        map.put("reportDate" , "2020-9-19");
        map.put("todayNewMember" , 100);
        map.put("totalMember" , 1000);
        map.put("thisWeekNewMember" , 200);
        map.put("thisMonthNewMember" , 400);
        map.put("todayOrderNumber" , 100);
        map.put("todayVisitsNumber" , 90);
        map.put("thisWeekOrderNumber" , 150);
        map.put("thisWeekVisitsNumber" , 140);
        map.put("thisMonthOrderNumber" , 300);
        map.put("thisMonthVisitsNumber" , 280);
        List<Map> list = new ArrayList<>();
        Map map1 = new HashMap();
        map1.put("name" , "入职体检套餐");
        map1.put("setmeal_count" , 300);
        map1.put("proportion" , 0.33);

        Map map2 = new HashMap();
        map2.put("name" , "健康爸妈套餐");
        map2.put("setmeal_count" , 400);
        map2.put("proportion" , 0.55);

        list.add(map1);
        list.add(map2);
        map.put("hotSetmeal" , list);
        return new Result(true , MessageConstant.GET_BUSINESS_REPORT_SUCCESS , map);*/

        try {
            Map<String , Object> map = reportService.getBusinessReportData();
            return new Result(true , MessageConstant.GET_BUSINESS_REPORT_SUCCESS , map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据报表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request , HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            String filePath = request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //得到第一个工作表
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            XSSFRow row = sheetAt.getRow(2);//得到第三行
            XSSFCell cell = row.createCell(5);//得到第五列
            cell.setCellValue(reportDate);//添加时间

            row = sheetAt.getRow(4); //得到第五行
            row.createCell(5).setCellValue(todayNewMember);//本日新增会员数
            row.createCell(7).setCellValue(totalMember);//总会员数

            row = sheetAt.getRow(5); //得到第六行
            row.createCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.createCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheetAt.getRow(7); //得到第八行
            row.createCell(5).setCellValue(todayOrderNumber); //今日预约数
            row.createCell(7).setCellValue(todayVisitsNumber); //今日到诊数

            row = sheetAt.getRow(8); //得到第九行
            row.createCell(5).setCellValue(thisWeekOrderNumber); //本周预约数
            row.createCell(7).setCellValue(thisWeekVisitsNumber); //本周到诊数

            row = sheetAt.getRow(9); // 得到第十行
            row.createCell(5).setCellValue(thisMonthOrderNumber); //本月预约数
            row.createCell(7).setCellValue(thisMonthVisitsNumber); //本月就诊数

            int rowNumber = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name"); //套餐名称
                Long setmeal_count = (Long) map.get("setmeal_count"); //套餐预约人数
                BigDecimal proportion = (BigDecimal) map.get("proportion"); //热门套擦预约人数占总人数比
                row = sheetAt.getRow(rowNumber ++);
                row.createCell(4).setCellValue(name);
                row.createCell(5).setCellValue(setmeal_count);
                row.createCell(6).setCellValue(proportion.doubleValue());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");

            xssfWorkbook.write(outputStream);
            outputStream.flush();
            xssfWorkbook.close();
            outputStream.close();

            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
}
